package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import com.leyou.pojo.dto.GroupDTO;
import com.leyou.pojo.dto.ParamDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper,SpecGroup> implements SpecGroupService {

    @Autowired
    SpecParamService specParamService;
    //新增/修改规格组
    @Override
    @Transactional
    public void addOrUpdateSpecGroup(GroupDTO groupDTO) {
        SpecGroup specGroup = groupDTO.toEntity(SpecGroup.class);
        this.saveOrUpdate(specGroup);
    }

    //根据商品分类id，查询规格组的集合
    @Override
    public List<GroupDTO> findGroudsByCategoryId(Long id) {
        return GroupDTO.convertEntityList(this.query().eq("category_id",id).list());
    }

    //根据分类id查询规格组及组内参数
    @Override
    public List<GroupDTO> findGroudsAndParamsByCategoryId(Long cid) {

        //根据商品分类id，查询规格组的集合
        List<GroupDTO> groupDTOS = findGroudsByCategoryId(cid);
        //获取规格组id集合
//        List<Long> groupIds = groupDTOS
//                .stream()
//                .map(GroupDTO::getId)
//                .collect(Collectors.toList());
        //查询组内参数
        List<SpecParam> params = specParamService
                .query()
                .eq("category_id", cid)
                .list();
        List<ParamDTO> paramDTOS = ParamDTO.convertEntityList(params);
        //以groupId对paramDTOS分组
        Map<Long, List<ParamDTO>> patamMap = paramDTOS.stream().collect(Collectors.groupingBy(ParamDTO::getGroupId));

        //将分组后的params存入到对应的GroupDTO中
        for (GroupDTO groupDTO : groupDTOS) {
            groupDTO.setParams(patamMap.get(groupDTO.getId()));
        }
        return groupDTOS;
        //return GroupDTO.convertEntityList(baseMapper.findGroudsAndParamsByCategoryId(cid));
    }


}
